package com.wx.web.controller.trade;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyun.oss.common.utils.DateUtil;
import com.eachonline.core.JsonResult;
import com.eachonline.core.Pagination;
import com.eachonline.util.StringUtil;
import com.wx.business.trade.IxbTradeRecordService;
import com.wx.business.util.OrderNoGenerater;
import com.wx.business.util.PayTypeStatus;
import com.wx.business.util.TradeNoGenerater;
import com.wx.business.util.TradeStatus;
import com.wx.business.util.TradeType;
import com.wx.model.IxbTradeRecord;
import com.wx.model.IxbTradeRecordExample;
import com.wx.model.IxbUser;
import com.wx.model.base.BaseIxbTradeRecordExample.Criteria;

/**
 * 交易记录控制器
 *
 * @author fengshuonan
 * @Date 2018-08-13 10:12:59
 */
@Controller
@RequestMapping("/ixbTradeRecord")
public class IxbTradeRecordController {

	
	@Autowired
	public IxbTradeRecordService ixbTradeRecordService;
	
    /**
     * 新增交易记录
     */
    @RequestMapping(value = "/h5/create")
    @ResponseBody
    public JsonResult create(String buyerId,String buyerName,String courseId,String courseName,double tradeFee) {
    	IxbTradeRecord record=new IxbTradeRecord();
    	String tradeNo=TradeNoGenerater.getInstance().generaterPayTradeNo();
     	String orderNo=OrderNoGenerater.getInstance().generaterCourseOrderNo();
     	
    	record.setUserId(buyerId);
    	record.setUserName(buyerName);
    	record.setCourseId(courseId);
    	record.setCourseName(courseName);
    	record.setCreateTime(new Date());
    	record.setOrderNo(orderNo);
    	record.setPayType(PayTypeStatus.ZF_WX);
    	record.setTradeFee(tradeFee);
    	record.setTradeNo(tradeNo);
    	record.setTradeStatus(TradeStatus.TRADE_PAY);
    	record.setTradeType(TradeType.JZ_ZXZF);
        ixbTradeRecordService.insert(record);
        
        return new JsonResult(true, record);
    }


    /**
     * tradeType  0 提现   3 交易佣金
     * 交易佣金记录列表
     * monthTime  参数  例如：2018-07
     */
    @RequestMapping(value = "/commission/list")
    @ResponseBody
    public JsonResult withdrawMoneyList(HttpServletRequest request,String monthTime,int start ,int pageSize,int  tradeType) {
		IxbUser user=(IxbUser) request.getSession().getAttribute("currentAccount");
		IxbTradeRecordExample ext=new IxbTradeRecordExample();
		Criteria cri= ext.createCriteria().andUserIdEqualTo(user.getSid());
		if(StringUtil.isNotEmpty(tradeType+""))
		{
			cri.andTradeTypeEqualTo(tradeType);
		}
		try {
			cri.andCreateTimeBetween(parseTwoTime(monthTime).get("A"),parseTwoTime(monthTime).get("B") );
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			return new JsonResult(false, "时间格式不正确");
		}
		
		
		Pagination<IxbTradeRecord> pageInfo= ixbTradeRecordService.queryByPage(ext, start, pageSize, " create_time desc");
		Map<String,Object>  result=new HashMap<String,Object>();
		result.put("data", pageInfo);
		return new JsonResult(true, result);
    }
    

    
    /**
     * A 月的起始时间
     * B 月的结束时间
     * @param args
     * @throws ParseException
     */
    public static Map<String,Date> parseTwoTime(String  monthTime) throws ParseException {
    	
    	Map<String,Date> mTime=new HashMap<String, Date>();
  		Calendar c=Calendar.getInstance();
  		if(StringUtil.isNotEmpty(monthTime))
    	{
  			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
  	  		Date nowTime =sdf.parse(monthTime);
  	  		c.setTime(nowTime);
    	}
  		
  		int lastMonthMaxDay=c.getActualMaximum(Calendar.DAY_OF_MONTH);
  		c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), lastMonthMaxDay, 23, 59, 59);
  		mTime.put("B", c.getTime());
  		
  		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-01  00:00:00");
  		String gtime2 = sdf2.format(c.getTime()); //上月第一天
  	    
  		mTime.put("A", sdf2.parse(gtime2));
  		
  		return  mTime;
  		
  	}

    /**
     * 提现
     */
    @RequestMapping(value = "/withdraw")
    @ResponseBody
    public JsonResult withdraw(HttpServletRequest request,String cardId,double tradeFee) {
    	IxbUser user=(IxbUser) request.getSession().getAttribute("currentAccount");
    	
    	IxbTradeRecord record=new IxbTradeRecord();
    	String tradeNo=TradeNoGenerater.getInstance().generaterIncomeTradeNo();
     	String orderNo=tradeNo;
     	
    	record.setUserId(user.getSid());
    	record.setUserName(user.getUserName());
    	record.setCreateTime(new Date());
    	record.setOrderNo(orderNo);
    	record.setPayType(PayTypeStatus.ZF_YEZF);
    	record.setTradeFee(tradeFee);
    	record.setTradeNo(tradeNo);
    	record.setTradeStatus(TradeStatus.TRADE_RECEIPT);
    	record.setTradeType(TradeType.JZ_TX);
        ixbTradeRecordService.insert(record);
        
        return new JsonResult(true, record);
    }


    /**
     * 3 交易佣金
     * 交易佣金记录列表
     * monthTime  参数  例如：2018-07
     * 
     * 
     * SELECT 
		 r.*,
		  e.`agency_name`,
		  p.`business_pic` 
		FROM
		  ixb_trade_record r,
		  ixb_business_picture p,
		  (SELECT  d.sid ,a.`agency_name` FROM  ixb_course_detail d,
		  ixb_training_agency a  WHERE d.`publisher_id`=a.`sid`) e
		  
		WHERE p.`business_id` = e.`sid` 
		  AND r.`course_id` = e.`sid` 
		  AND p.`is_main` = 1 
		  AND  r.`course_id`=e.sid
		     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public JsonResult commissionList(HttpServletRequest request,String monthTime,int start ,int pageSize) {
		IxbUser user=(IxbUser) request.getSession().getAttribute("currentAccount");
		IxbTradeRecordExample ext=new IxbTradeRecordExample();
		
		try {
			Map<String,Date>  timeMap=parseTwoTime(monthTime);
			ext.setStartTime(timeMap.get("A"));
			ext.setEndTime(timeMap.get("B"));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			return new JsonResult(false, "时间格式错误"); 
		}
		ext.setUserId(user.getSid());
		Pagination<Map<String,Object>> pageInfo= ixbTradeRecordService.queryCommTradeRecordByPage(start, pageSize, ext);
		Map<String,Object>  result=new HashMap<String,Object>();
		result.put("data", pageInfo);
		return new JsonResult(true, result);
    }
    

    
}
